package phoeics.authoryserver.webservice.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import phoeics.authoryserver.webservice.entity.OauthUser;
import phoeics.authoryserver.webservice.repository.OauthUserRepository;
import phoeics.authoryserver.webservice.service.AuthService;
@Service
public class AuthServiceImpl implements AuthService{
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AuthServiceImpl.class);
	@Autowired
	private AuthenticationManager authenticationManager;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	 OauthUserRepository oauthUserRepository;
	@Override
	public OauthUser register(OauthUser user) {
		 final String username = user.getUsername();
		 //OauthUser oauthUser=oauthUserRepository.findByUsername(username);
		 if(oauthUserRepository.findByUsername(username)!=null){
			 return null;
		 }
		 BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		 final String rawPassword = user.getPassword();
		 user.setPassword(encoder.encode(rawPassword));
	     //final String email = userToAdd.getEmail();
		return oauthUserRepository.save(user);
	}

	@Override
	public String login(String username, String password) {
		 UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
		 final Authentication authentication = authenticationManager.authenticate(upToken);
		 SecurityContextHolder.getContext().setAuthentication(authentication);
		 final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		return null;
	}

	@Override
	public String refresh(String oldToken) {
		// TODO Auto-generated method stub
		return null;
	}

	
}
